#include "MyThreadPool.h"
#include <unistd.h>

namespace myrpc
{
	namespace mythread
	{
		pthread_mutex_t MyThreadPool::_queuelock = PTHREAD_MUTEX_INITIALIZER;
		std::queue<MyThreadPool::WorkNode*> MyThreadPool::_workqueue;
		int MyThreadPool::fd[2] = {0 , 0};
		
		MyThreadPool::MyThreadPool()
		{
		
			_threadnumb = DEAULT_THREAD_NUMBER;
			_queuemaxsize = DEAULT_QUEUE_NUMBER;
		}
		
		
		MyThreadPool::~MyThreadPool()
		{
		
		}
		
		int MyThreadPool::Add(ThreadProc func, void* data)
		{
			WorkNode* pNode = new WorkNode;
			pNode->data = data;
			pNode->threadproc = func;
			pthread_mutex_lock(&_queuelock);
			_workqueue.push(pNode);
			write(fd[1], "", 1);
			pthread_mutex_unlock(&_queuelock);
			return 0;
		}
		
		void MyThreadPool::Start()
		{	
			pipe(MyThreadPool::fd);
			for (size_t i = 0; i < _threadnumb; i++)
			{
				Thread* thread = new Thread;
				thread->id = i;
				thread->stat = WAITING;
				int ret = pthread_create(&thread->pid, NULL, Threadfuction, thread);
				_vecThread.push_back(thread);
			}
		}
		
		void* MyThreadPool::Threadfuction(void* data)
		{	
			MyThreadPool::Thread*  thread = (Thread*)data;
			char buf[1];
			for (;;)
			{	
				read(fd[0], buf, 1);
				pthread_mutex_lock(&_queuelock);
				WorkNode* worknode = _workqueue.front();
				_workqueue.pop();
				pthread_mutex_unlock(&_queuelock);
				thread->stat =RUNNING;
				worknode->threadproc(data);
				thread->stat = WAITING;
			}
		
		}
	}
}
